package com.example.calendarutildemo.calendar;

import android.Manifest;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class SignRemindDialogFragment extends BaseDialogFragment implements View.OnClickListener{

    private TextView mRemindBtn;
    private TextView mCancelBtn;
    private TextView mNoRemindBtn;
    private ImageView mClose;

    public static String mTitle0 = "【充电来钱】您的清晨红包已到账，24:00前不领作废";
    public static String mTitle1 = "【充电来钱】您的午间红包已到账，24:00前不领作废";
    public static String mTitle2 = "【充电来钱】您的晚上红包已到账，24:00前不领作废";
    //public static String mTitle3 = "【充电来钱】您的步数该兑换了，24:00前不兑换作废";

    @Override
    protected int setLayoutId() {
        return R.layout.dialog_sign_remind;
    }

    @Override
    protected void initKeyListener() {
        this.getDialog().setOnKeyListener(new DialogInterface.OnKeyListener(){

            @Override
            public boolean onKey(DialogInterface arg0, int keyCode, KeyEvent arg2) {
                if (keyCode == KeyEvent.KEYCODE_BACK){
                    onDismiss();
                    return false;
                } else if (keyCode == KeyEvent.KEYCODE_MENU){
                    return false;
                }
                return false;
            }
        });
    }

    @Override
    protected void initView(View view) {
        TAG = "SignRemindDialogFragment";
        mClose = view.findViewById(R.id.dialog_close);
        mRemindBtn = view.findViewById(R.id.qd_remind_btn);
        mCancelBtn = view.findViewById(R.id.qd_cancel_btn);
        mNoRemindBtn = view.findViewById(R.id.no_remind_btn);

        mClose.setOnClickListener(this);
        mRemindBtn.setOnClickListener(this);
        mCancelBtn.setOnClickListener(this);
        mNoRemindBtn.setOnClickListener(this);
    }

    private void onDismiss() {
        super.onDismiss(true);
    }

    public static SignRemindDialogFragment getInstance() {
        SignRemindDialogFragment dialog = new SignRemindDialogFragment();
        Bundle bundle = new Bundle();
        dialog.setArguments(bundle);
        return dialog;
    }

    @Override
    public void show(FragmentManager manager, String tag) {
        if (manager == null || manager.beginTransaction() == null){
            return;
        }
        isLoadTTAd = false;
        isLoadGdAd = false;
        module_type = tag;
        LogUtil.d(tag,"===上报模块===");
        super.show(manager, tag);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.dialog_close:
                onDismiss();
                break;
            case R.id.qd_remind_btn:
                fetchPermission();
                break;
            case R.id.qd_cancel_btn:
                clickCancelBtn();
                break;
            case R.id.no_remind_btn:
                Hawk.put(BusinessConsDef.KEY_NO_SHOW_REMIND_DIALOG,true);
                onDismiss();
                break;
        }
    }

    private void clickCancelBtn() {
        boolean isShowedExitDialog = SignInUtils.isTodaySignIn(SignInUtils.POSITION_REMIND);
        if (!AdCodeIdUtils.isOldUser() && Hawk.get(BusinessConsDef.KEY_NEW_USER_CLICK_AD, true)){
            Hawk.put(BusinessConsDef.KEY_NEW_USER_CLICK_AD, false);
            if (mFeedAdType == AdCodeIdUtils.AD_FEED_TYPE_TT){
                if(ClickTTAdRandom.PercentageNormalRandom() == AdCodeIdUtils.AD_CLICK_TT_AD && !isLoadGdAd){
                    clickAd();
                    NExecutor.postUIDelay(new NTask(){
                        @Override
                        public void run() {
                            isShowing = false;
                            onDismiss();
                        }
                    }, ClickUtil.dialogDelayDismissTime);
                }
            }
        } else {
            if (isShowedExitDialog){
                finish();
            }
            onDismiss();
        }
        if (!isShowedExitDialog){
            EventBus.getDefault().post(new ExitAppEvent(true));
            onDismiss();
        }
    }

    private void fetchPermission() {
        int checkSelfPermission;
        try {
            checkSelfPermission = ActivityCompat.checkSelfPermission(mActivity, Manifest.permission.WRITE_CALENDAR);
        } catch (RuntimeException e) {
            e.printStackTrace();
            return;
        }

        // 如果有授权，走正常插入日历逻辑
        if (checkSelfPermission == PackageManager.PERMISSION_GRANTED){
            insertCalendar(mTitle0, getTimeInMillis(0), 5);
            /*insertCalendar(mTitle1, getTimeInMillis(1), 20);
            insertCalendar(mTitle2, getTimeInMillis(2), 5);*/
            //insertCalendar(mTitle3,getTimeInMillis(3),60);
            return;
        } else {
            // 如果没有授权，就请求用户授权
            ActivityCompat.requestPermissions(mActivity, new String[]{Manifest.permission.WRITE_CALENDAR,
                    Manifest.permission.READ_CALENDAR}, 100);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 100){
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                // 用户同意的授权请求
                insertCalendar(mTitle0, getTimeInMillis(0), 5);
                /*insertCalendar(mTitle1, getTimeInMillis(1), 20);
                insertCalendar(mTitle2, getTimeInMillis(2), 5);*/
                //insertCalendar(mTitle3,getTimeInMillis(3),60);
            } else {

            }
        }
    }

    private long getTimeInMillis(int type) {
        long time = System.currentTimeMillis();
        switch (type) {
            case 0:
                Calendar calendar = new GregorianCalendar();
                calendar.setTime(new Date());
                calendar.add(Calendar.DATE, 1);
                calendar.set(Calendar.HOUR_OF_DAY, 8);
                calendar.set(Calendar.MINUTE, 30);
                calendar.set(Calendar.SECOND, 0);
                time = calendar.getTimeInMillis();
                break;

            case 1:
                Calendar calendar1 = new GregorianCalendar();
                calendar1.setTime(new Date());
                calendar1.add(Calendar.DATE, 1);
                calendar1.set(Calendar.HOUR_OF_DAY, 12);
                calendar1.set(Calendar.MINUTE, 15);
                calendar1.set(Calendar.SECOND, 0);
                time = calendar1.getTimeInMillis();
                break;

            case 2:
                Calendar calendar2 = new GregorianCalendar();
                calendar2.setTime(new Date());
                calendar2.add(Calendar.DATE, 1);
                calendar2.set(Calendar.HOUR_OF_DAY, 18);
                calendar2.set(Calendar.MINUTE, 30);
                calendar2.set(Calendar.SECOND, 0);
                time = calendar2.getTimeInMillis();
                break;

            case 3:
                Calendar calendar3 = new GregorianCalendar();
                calendar3.setTime(new Date());
                calendar3.add(Calendar.DATE, 1);
                calendar3.set(Calendar.HOUR_OF_DAY, 20);
                calendar3.set(Calendar.MINUTE, 0);
                calendar3.set(Calendar.SECOND, 0);
                time = calendar3.getTimeInMillis();
                break;
        }
        return time;
    }

    private void insertCalendar(String title, long time, int Duration) {
        if (isFinish()){
            return;
        }
        String location = Hawk.get(BusinessConsDef.KEY_LOCATION, "");
        CalendarEvent calendarEvent = new CalendarEvent(
                title,
                "连续签到7天获得更多金币",
                location,
                time,
                time + Duration * 60 * 1000,
                0, RRuleConstant.REPEAT_CYCLE_DAILY_FOREVER
        );

        // 添加事件
        int result = CalendarProviderManager.addCalendarEvent(mActivity, calendarEvent);
        if (result == 0){
            LogUtil.e(TAG, "添加提醒成功");
            ToastUtils.showShort("添加提醒成功");
        } else if (result == -1){
            LogUtil.e(TAG, "添加提醒失败");
        } else if (result == -2){
            LogUtil.e(TAG, "没有权限");
        }
        dismissAllowingStateLoss();
    }

    private void finish() {
        if (mActivity != null){
            mActivity.finish();
        }
    }

}